import { ChangeDetectorRef, Component, ViewChild, ViewRef, OnInit } from '@angular/core';
import { STColumn, STComponent, STData, STPage, STRes } from '@delon/abc/st';
import { SFSchema } from '@delon/form';
import { _HttpClient, ModalHelper } from '@delon/theme';
import { ModalHelperOptions } from '@delon/theme/src/services/modal/modal.helper';
import format from 'date-fns/format';
import * as _ from 'lodash';
import * as moment from 'moment';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalRef, NzModalService } from 'ng-zorro-antd/modal';
import { zip } from 'rxjs';
import { finalize } from 'rxjs/operators';

@Component({
  selector: 'app-business-refund-process',
  templateUrl: './refund-process.component.html'
})
export class BusinessRefundProcessComponent implements OnInit {
  i: any;
  itemCurrent: any;
  process_list: any;
  process_list_read: any;

  public st!: this;

  setDefaultStatus = {
    '0': { index: 0, text: '设为默认', notice: '设为默认', tooltip: '点击设为默认', color: '#36CFC9' },
    '1': { index: 1, text: '已为默认', notice: '已为默认', tooltip: '点击取消默认', color: 'blue' }
  };

  constructor(
    private modal: NzModalRef,
    private modal2: ModalHelper,
    private modal3: NzModalService,
    private msgSrv: NzMessageService,
    private http: _HttpClient,
    private cdr: ChangeDetectorRef
  ) {}

  ngOnInit(): void {
    if (this.i.externalOrderId != '') {
      this.loadDataFromServer(this.i.shopId, this.i.externalOrderId, this.i.trackingNumber, this.i.ssuId);
    }
    this.cdr.detectChanges();
  }

  loadDataFromServer(shopId: number, externalOrderId: string, trackingNumber: string, ssuId: string) {
    this.http
      .get(`api/refund_process`, { shopId: shopId, externalOrderId: externalOrderId, trackingNumber: trackingNumber, ssuId: ssuId })
      .subscribe(res => {
        this.cdr.detectChanges();
        this.process_list = res?.data;
        if (shopId > 0 && this.process_list.list && this.process_list.list.length > 0) {
          for (let k in this.process_list.list) {
            if (!this.process_list.list[k]['shop_id'] || this.process_list.list[k]['shop_id'] == 0) {
              this.process_list.list[k]['shop_id'] = shopId;
            }
          }
        }
        this.process_list_read = _.cloneDeepWith(this.process_list);
      });
  }

  save(): void {
    if (this.process_list.list && this.process_list.list.length > 0) {
      var timezoneOffset = new Date().getTimezoneOffset(); // 获取当前时区, 返回当前时区与UTC相差的分钟数
      var correct_ts = new Date().getTime() + timezoneOffset * 60 * 1000;
      var timeAt = `${format(new Date(correct_ts), 'yyyy-MM-dd HH:mm:ss').replace(' ', 'T')}Z`;
      for (let k in this.process_list.list) {
        if (!this.process_list.list[k]['ID']) {
          this.process_list.list[k]['ID'] = 0;
        }
        if (this.process_list.list[k]['processDate']) {
          this.process_list.list[k]['processDate'] = moment(this.process_list.list[k]['processDate']).format('yyyy-MM-DD');
        }
        if (!this.process_list.list[k]['updateAt'] || this.process_list.list[k]['updateAt'] == '') {
          this.process_list.list[k]['updateAt'] = timeAt;
        }
        if (!this.process_list.list[k]['createAt'] || this.process_list.list[k]['createAt'] == '') {
          this.process_list.list[k]['createAt'] = timeAt;
        }
      }
    }

    //console.log(this.process_list);
    for (let k in this.process_list.list) {
      if (this.process_list.list[k]['processDate'] == '') {
        this.msgSrv.warning('请输入跟踪日期!');
        return;
      }
      if (this.process_list.list[k]['processContent'] == '') {
        this.msgSrv.warning('请输入跟踪进度!');
        return;
      }
    }

    this.cdr.detectChanges();

    this.http.put(`api/refund_process`, this.process_list.list).subscribe(res => {
      if (res.err_code != 0) {
        this.msgSrv.error(res.msg);
        return;
      }
      this.msgSrv.success(res.msg);
    });

    if (this.i.pobj) {
      setTimeout(() => {
        this.i.pobj.ngOnInit();
      }, 500);
    }

    this.close();
  }

  //添加
  add(shopId: number, externalOrderId: string, trackingNumber: string, ssuId: string): void {
    //console.log(shopId, externalOrderId, trackingNumber);
    this.cdr.detectChanges();

    //const clone_ = _.cloneDeepWith(this.process_list);

    let copy_ = { list: [], total: 0 };
    for (let k in this.process_list.list) {
      copy_.list[k] = this.process_list.list[k];
    }

    var timezoneOffset = new Date().getTimezoneOffset(); // 获取当前时区, 返回当前时区与UTC相差的分钟数
    var correct_ts = new Date().getTime() + timezoneOffset * 60 * 1000;
    var timeAt = `${format(new Date(correct_ts), 'yyyy-MM-dd HH:mm:ss').replace(' ', 'T')}Z`;
    var ID = 0;
    var elem = {
      ID: ID,
      externalOrderId: `${externalOrderId}`,
      trackingNumber: trackingNumber,
      ssuId: ssuId,
      shop_id: shopId,
      sort: 0,
      processDate: '',
      processContent: '',
      updateUser: '',
      updateAt: timeAt,
      createUser: '',
      createAt: timeAt
    };
    // @ts-ignore
    copy_.list.push(elem);
    copy_.total = copy_.list.length;

    this.process_list = copy_;
    //console.log(this.process_list);
  }

  del(i: number): void {
    //if (confirm('是否删除该条信息？')) {
    //console.log(i);

    if (i != this.process_list.list.length - 1) {
      return;
    }

    let copy_ = { list: [], total: 0 };
    if (i == 0) {
      this.process_list.list[0]['processDate'] = '';
      this.process_list.list[0]['processContent'] = '';
      for (let k in this.process_list.list) {
        copy_.list[k] = _.cloneDeepWith(this.process_list.list[k]);
      }
    } else {
      for (let k in this.process_list.list) {
        if (parseInt(k) != i) {
          copy_.list[k] = _.cloneDeepWith(this.process_list.list[k]);
        }
      }
    }
    copy_.total = copy_.list.length;

    this.process_list = copy_;
    this.cdr.detectChanges();
    //}
  }

  datePickerChange(value: any) {
    //console.log(moment(value).format('yyyy-MM-DD'));
  }

  getLastUpdatorInfo() {
    var updateUser = '';
    var updateAt = '';
    for (let item of this.process_list_read.list) {
      if (!updateAt || updateAt <= item.updateAt) {
        updateUser = item.updateUser;
        updateAt = item.updateAt;
      }
    }
    var data = { updateUser: updateUser, updateAt: this.correctDatetime(updateAt) };
    return data;
  }

  correctDatetime(value: any) {
    if (value) {
      value = value.replace('T', ' ').replace('Z', '');
      var timezoneOffset = new Date().getTimezoneOffset(); // 获取当前时区, 返回当前时区与UTC相差的分钟数
      var correct_ts = new Date(value).getTime() - timezoneOffset * 60 * 1000;
      var date = new Date(correct_ts);
      let Y = date.getFullYear(),
        M = date.getMonth() + 1 < 10 ? `0${date.getMonth() + 1}` : date.getMonth() + 1,
        D = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate(),
        h = date.getHours() < 10 ? `0${date.getHours()}` : date.getHours(),
        m = date.getMinutes() < 10 ? `0${date.getMinutes()}` : date.getMinutes(),
        s = date.getSeconds() < 10 ? `0${date.getSeconds()}` : date.getSeconds();
      value = `${Y}-${M}-${D} ${h}:${m}:${s}`;
    }
    return value;
  }

  close(): void {
    this.modal.destroy();
  }
}
